package com.hzz.web.boss.user;

import com.hzz.api.user.IUserService;
import com.hzz.dto.user.AuthUserVsRoleDto;
import com.hzz.dto.user.UserDto;
import com.hzz.framework.Response;
import com.hzz.framework.annotation.ALogOperation;
import com.hzz.framework.annotation.auth.Logical;
import com.hzz.framework.annotation.auth.RequiresPermissions;
import com.hzz.framework.config.EncryptConfig;
import com.hzz.framework.security.CryptoJSDES;
import com.hzz.framework.security.MD5;
import com.hzz.framework.util.CommonConstant;
import com.hzz.framework.util.EhcacheUtil;
import com.hzz.framework.util.JwtUtil;
import com.hzz.framework.util.ValidatorUtil;
import com.hzz.framework.web.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api("员工管理")
@RestController
@Slf4j
public class StaffController extends BaseController {
    private static final String acPrefix = "/boss/staff/";
    @Autowired
    EncryptConfig encryptConfig;
    @Autowired
    IUserService staffService;
    @Autowired
    private EhcacheUtil cache;

    /**
     * <p> 信息分页 (未删除)。
     */
    @RequiresPermissions("user:menu")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "page/{pageNum}")
    // @ApiOperation(value = "信息分页")
    public Response page(@ModelAttribute UserDto dto, @PathVariable("pageNum") Integer pageNum) {
        log.info("page.........");
        Response result = new Response();
        try {
            dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
            dto.setPageNum(pageNum);
            dto.setDelFlag(0);
            UserDto userDto = JwtUtil.getSubject(UserDto.class);
            dto.setIsSuper(userDto.getIsSuper());
            result.data = getPageDto(staffService.findDataIsPage(dto));
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

//    /**
//     * <p> 回收站 (已删除)。
//     */
//    @RequiresPermissions("user:menu")
//    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "recyclePage/{pageNum}")
//    // @ApiOperation(value = "回收站 分页")
//    public Response recyclePage(@ModelAttribute UserDto dto, @PathVariable("pageNum") Integer pageNum) {
//        log.info("recyclePage.........");
//        Response result = new Response();
//        try {
//            dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
//            dto.setPageNum(pageNum);
//            dto.setDelFlag(1);
//            result.data = getPageDto(staffService.findDataIsPage(dto));
//        } catch (Exception e) {
//            result = Response.error(e.getMessage());
//        }
//        return result;
//    }

    @RequiresPermissions("user:menu")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "info/{id}")
    // @ApiOperation(value = "详情-根据id")
    public Response info(@PathVariable("id") Long id) {
        log.info("info.........");
        Response result = new Response();
        try {
            UserDto dto = new UserDto();
            dto.setId(id);
            result.data = staffService.findDataById(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    /**
     * <li>逻辑删除。
     */
    @RequiresPermissions("user:del")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "del/{id}")
    @ALogOperation(type = "删除", desc = "员工管理")
    // @ApiOperation(value = "逻辑删除")
    public Response del(@PathVariable("id") Long id) {
        log.info("del.........");
        Response result = new Response(0, "success");
        try {
            UserDto staff = JwtUtil.getSubject(UserDto.class);
            if (staff.getId().equals(id)) {
                throw new RuntimeException("不能删除自己!");
            }
            UserDto dto = new UserDto();
            dto.setId(id);
            dto.setCreateId(staff.getId());
            result.message = staffService.deleteDataById(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
//
//    /**
//     * <li>恢复。
//     */
//    @RequiresPermissions("user:recovery")
//    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "recovery/{id}")
//    @ALogOperation(type = "恢复", desc = "员工管理")
//    // @ApiOperation(value = "恢复")
//    public Response recovery(@PathVariable("id") Long id) {
//        log.info("del.........");
//        Response result = new Response(0, "success");
//        try {
//            UserDto dto = new UserDto();
//            dto.setId(id);
//            UserDto staffDto = JwtUtil.getSubject(UserDto.class);
//            dto.setUserId(staffDto.getId());
//            dto.setIsSuper(staffDto.getIsSuper());
//            result.message = staffService.recoveryDataById(dto);
//        } catch (Exception e) {
//            result = Response.error(e.getMessage());
//        }
//        return result;
//    }

    /**
     * 判断员工id是否存在
     */
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "isAccountExist/{account}")
    // @ApiOperation(value = "判断员工[账号]是否存在")
    public Response isAccountExist(@PathVariable("account") String account) {
        Response result = new Response(0, "success");
        try {
            result.data = staffService.isAccountExist(account);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    /**
     * <p> 信息保存
     */
    @RequiresPermissions(value = {"user:add", "user:edit"}, logical = Logical.OR)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "save")
    @ALogOperation(type = "修改", desc = "员工管理")
    // @ApiOperation(value = "信息保存")
    public Response save(@Validated @ModelAttribute UserDto dto, BindingResult bindingResult) {
        log.info("save.........");
        Response result = new Response(0, "success");
        try {
            if (bindingResult.hasErrors()) {
                String errorresult = "";
                List<ObjectError> errorList = bindingResult.getAllErrors();
                for (ObjectError error : errorList) {
                    errorresult += (error.getDefaultMessage()) + ";";
                }
                result = Response.error(errorresult);
            } else {
                UserDto staff = JwtUtil.getSubject(UserDto.class);
                if (ValidatorUtil.isEmpty(dto.getAccount())) {
                    dto.setAccount(staff.getAccount());
                    dto.setCreateId(staff.getId());
                }
                dto.setGender(2);
                dto.setType(CommonConstant.TYPE_管理员);
                dto.setCreateId(staff.getId());
                // password: that.encrypt(encrypt.key, CryptoJS.MD5(that.password).toString()),
                if (ValidatorUtil.notEmpty(dto.getPassword())) {
                    dto.setPassword(CryptoJSDES.desDecrypt(dto.getPassword(), MD5.md5Hex(encryptConfig.getPRIKEY())));
                }
                // confirmPassword: that.encrypt(encrypt.key, CryptoJS.MD5(that.confirmPassword).toString()),
                if (ValidatorUtil.notEmpty(dto.getConfirmPassword())) {
                    dto.setConfirmPassword(CryptoJSDES.desDecrypt(dto.getConfirmPassword(), MD5.md5Hex(encryptConfig.getPRIKEY())));
                }
                result = staffService.saveOrUpdateData(dto);
            }
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    /**
     * <p> 个人信息更新
     */
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "ownupdate")
    @ALogOperation(type = "修改", desc = "个人信息更新")
    // @ApiOperation(value = "信息保存")
    public Response ownupdate(@ModelAttribute UserDto dto) {
        log.info("ownupdate.........");
        Response result = new Response(0, "success");
        try {
            UserDto staff = JwtUtil.getSubject(UserDto.class);
            dto.setId(staff.getId());
            dto.setCreateId(staff.getId());
            result.data = staffService.updateData(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    /**
     * <p> 个人密码修改
     */
    @RequestMapping(method = {RequestMethod.POST}, value = acPrefix + "update/ownpassword")
    @ALogOperation(type = "修改", desc = "个人密码修改")
    // @ApiOperation(value = "密码修改")
    public Response ownpassword(@ModelAttribute UserDto dto) {
        log.info("ownpassword.........");
        Response result = new Response(0, "success");
        try {
            if (dto == null || ValidatorUtil.isNullEmpty(dto.getOriginalPassword()) || ValidatorUtil.isNullEmpty(dto.getNewPassword()) || ValidatorUtil.isNullEmpty(dto.getConfirmPassword())) {
                return Response.error("提交数据不完整!");
            }
            if (!dto.getNewPassword().equals(dto.getConfirmPassword())) {
                throw new RuntimeException("两次密码不一致!");
            }
//           originalPassword: that.encrypt(encrypt.key, CryptoJS.MD5(that.originalPassword).toString()),
            if (ValidatorUtil.notEmpty(dto.getOriginalPassword())) {
                dto.setOriginalPassword(CryptoJSDES.desDecrypt(dto.getOriginalPassword(), MD5.md5Hex(encryptConfig.getPRIKEY())));
            }
//           newPassword: that.encrypt(encrypt.key, CryptoJS.MD5(that.newPassword).toString()),
            if (ValidatorUtil.notEmpty(dto.getNewPassword())) {
                dto.setNewPassword(CryptoJSDES.desDecrypt(dto.getNewPassword(), MD5.md5Hex(encryptConfig.getPRIKEY())));
            }
//           confirmPassword: that.encrypt(encrypt.key, CryptoJS.MD5(that.confirmPassword).toString())
            if (ValidatorUtil.notEmpty(dto.getConfirmPassword())) {
                dto.setConfirmPassword(CryptoJSDES.desDecrypt(dto.getConfirmPassword(), MD5.md5Hex(encryptConfig.getPRIKEY())));
            }
            dto.setId(JwtUtil.getSubject(UserDto.class).getId());
            result.message = staffService.updatePassword(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    @RequiresPermissions("user:edit:resetpwd")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "reset/password/{id}")
    @ALogOperation(type = "修改", desc = "员工密码重置")
    // @ApiOperation(value = "员工密码重置")
    public Response resetPwd(@PathVariable("id") Long id) {
        log.info("resetPwd.........");
        Response result = new Response(0, "success");
        try {
            UserDto dto = new UserDto();
            dto.setId(id);
            result.data = staffService.resetPassword(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

//    @RequiresPermissions("user:menu")
//    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "get/org/{userId}")
//    // @ApiOperation(value = "获取所属组织")
//    public Response getUser(@PathVariable("userId") Long userId) {
//        log.info("getUser.........");
//        Response result = new Response(0, "success");
//        try {
//            UserDto dto = new UserDto();
//            dto.setId(userId);
//            result.data = staffService.findOrgIsList(dto);
//        } catch (Exception e) {
//            result = Response.error(e.getMessage());
//        }
//        return result;
//    }
//
//    @RequiresPermissions("user:edit:org")
//    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "add/org")
//    @ALogOperation(type = "添加组织", desc = "员工管理")
//    // @ApiOperation(value = "添加组织")
//    public Response addOrg(@ModelAttribute AuthUserVsOrgDto dto) {
//        log.info("addOrg.........");
//        Response result = new Response(0, "success");
//        try {
//            if (dto == null) {
//                throw new RuntimeException("参数异常");
//            }
//            result = staffService.addOrg(dto);
//        } catch (Exception e) {
//            result = Response.error(e.getMessage());
//        }
//        return result;
//    }
//
//    @RequiresPermissions("user:edit:org")
//    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "del/org")
//    @ALogOperation(type = "删除组织", desc = "员工管理")
//    // @ApiOperation(value = "删除组织")
//    @RfUser2Bean
//    public Response delOrg(@ModelAttribute AuthUserVsOrgDto dto) {
//        log.info("delOrg.........");
//        Response result = new Response(0, "success");
//        try {
//            if (dto == null) {
//                throw new RuntimeException("参数异常");
//            }
//            result = staffService.delOrg(dto);
//        } catch (Exception e) {
//            result = Response.error(e.getMessage());
//        }
//        return result;
//    }

//    @RequiresPermissions("user:edit:org")
//    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "default/org")
//    @ALogOperation(type = "默认组织", desc = "员工管理")
//    // @ApiOperation(value = "默认组织")
//    @RfUser2Bean
//    public Response defaultOrg(@ModelAttribute AuthUserVsOrgDto dto) {
//        log.info("defaultOrg.........");
//        Response result = new Response(0, "success");
//        try {
//            if (dto == null) {
//                throw new RuntimeException("参数异常");
//            }
//            result.setData(staffService.defaultOrg(dto));
//        } catch (Exception e) {
//            result = Response.error(e.getMessage());
//        }
//        return result;
//    }

//    /**
//     * <p> 批量新增。
//     */
//    @RequiresPermissions("user:add:batch")
//    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "add/batch")
//    // @ApiOperation(value = "批量新增")
//    public Response addBatch(@RequestParam("fileUrl") String fileUrl) {
//        log.info("addBatch.........");
//        Response result = new Response(0, "success");
//        try {
//            result = staffService.addBatch(fileUrl);
//        } catch (Exception e) {
//            result = Response.error(e.getMessage());
//        }
//        return result;
//    }

    @RequiresPermissions("user:menu")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "get/role/byuser/{userId}")
    // @ApiOperation(value = "获取个人已设置角色")
    public Response getRoleByUser(@PathVariable("userId") Long userId) {
        log.info("getRoleByUser.........");
        Response result = new Response(0, "success");
        try {
            UserDto dto = new UserDto();
            dto.setId(userId);
            result.data = staffService.findUserRoleIsList(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    @RequiresPermissions("user:menu")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "get/role/byorg/{orgId}")
    // @ApiOperation(value = "获取组织已设置角色")
    public Response getRoleByOrg(@PathVariable("orgId") Long orgId) {
        log.info("getRoleByOrg.........");
        Response result = new Response(0, "success");
        try {
            UserDto dto = new UserDto();
            dto.setOrgId(orgId);
            result.data = staffService.findOrgRoleIsList(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    @RequiresPermissions("user:edit:role")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "add/role")
    @ALogOperation(type = "添加角色", desc = "员工管理")
    @ApiOperation(value = "添加角色")
    public Response addRole(@RequestBody AuthUserVsRoleDto dto) {
        log.info("addRole.........");
        Response result = new Response(0, "success");
        try {
            result = staffService.addRole(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    @RequiresPermissions("user:edit:role")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "del/role")
    @ALogOperation(type = "删除角色", desc = "员工管理")
    @ApiOperation(value = "删除角色")
    public Response delRole(@RequestBody AuthUserVsRoleDto dto) {
        log.info("delRole.........");
        Response result = new Response(0, "success");
        try {
            result = staffService.delRole(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
//
//    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "list/user/all")
//    @ApiOperation(value = "获取用户及用户所在组织")
//    public Response findUserAndOrgDataIsList() {
//        log.info("findUserAndOrgDataIsList.........");
//        Response result = new Response(0, "success");
//        try {
//            UserDto dto = new UserDto();
//            result.data = staffService.findUserAndOrgDataIsList(dto);
//        } catch (Exception e) {
//            result = Response.error(e.getMessage());
//        }
//        return result;
//    }

    /**
     * 禁用账号
     */
    @RequiresPermissions("user:disabled")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "disabled/{id}/{state}")
    // @ApiOperation(value = "offline")
    public Response disabled(@PathVariable("id") Long id, @PathVariable("state") Integer state) {
        log.info("disabled.........");
        Response result = new Response(0, "success");
        try {
            UserDto dto = new UserDto();
            dto.setId(id);
            dto.setState(state);
            result.data = staffService.disabled(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    /**
     * 强制下线
     */
    @RequiresPermissions("user:offline")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "offline/{id}")
    // @ApiOperation(value = "offline")
    public Response offline(@PathVariable("id") Long id) {
        log.info("offline.........");
        Response result = new Response(0, "success");
        try {
            cache.set(CommonConstant.JWT_OFFLINE + id, System.currentTimeMillis());//,CommonConstant.JWT_TTL, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }


    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "get/user/byrole/{roleId}/{pageNum}")
    @ApiOperation(value = "获取用户及用户所在组织")
    public Response findUserByRoleIsPage(@PathVariable("roleId") Long roleId, @PathVariable("pageNum") Integer pageNum) {
        log.info("findUserByRoleIsPage.........");
        Response result = new Response(0, "success");
        try {
            AuthUserVsRoleDto dto = new AuthUserVsRoleDto();
            dto.setPageSize(CommonConstant.PAGEROW_DEFAULT_COUNT);
            dto.setPageNum(pageNum);
            dto.setRoleId(roleId);
            result.data = getPageDto(staffService.findUserByRoleIsPage(dto));
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }
}
